﻿using System;
using System.Collections.Generic;
using System.Linq;
using Crm2011.Framework.Core;



namespace ScriptEase.Shell
{
    class MruList
    {
        private readonly List<string> _mruList;
        private readonly string _listName;
        private const int MaxItemCount = 8;

        public static readonly MruList Current = new MruList("ScriptEase.Projects.MRU.xml");


        public MruList(string listName)
        {
            _listName = listName;
            _mruList = IsolatedStorage.ReadFromDisc<List<string>>(_listName) ?? 
                       new List<string>();
        }



        public void Add(string item)
        {
            var existingItem = _mruList.FirstOrDefault(i => 0 == string.Compare(i, item, StringComparison.InvariantCultureIgnoreCase));
            if (existingItem != null)
                _mruList.Remove(existingItem);  // remove to be inserted on top

            if (_mruList.Count == MaxItemCount)
                _mruList.Remove(_mruList[MaxItemCount - 1]);
            
            _mruList.Insert(0, item);
            IsolatedStorage.SaveToDisc(_listName, _mruList);
        }



        public string MostRecent
        {
            get { return _mruList.Count > 0 ? _mruList[0] : null; }
        }
    }
}